package com.fcgzs.springboot.cfg;

import com.fcgzs.springboot.pojo.Permission;
import com.fcgzs.springboot.pojo.Role;
import com.fcgzs.springboot.pojo.User;
import com.fcgzs.springboot.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
@Component
@Service
public class MyUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //认证
        //通过用户名查询用户
        User userByUserName = userService.getUserByUserName(username);
        if(userByUserName == null){ //空值
            throw new UsernameNotFoundException("该用户不存在");
        }

        List<GrantedAuthority> list = new ArrayList<>();
        //授权：2种方式
        //通过用户id查询用户对应的角色信息
        List<Role> roleByUid = userService.getRoleByUid(userByUserName.getId());
        for (Role one : roleByUid) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_"+one.getKeyword()); //ROLE_admin ROLE_user
            list.add(simpleGrantedAuthority);
        }
        //通过用户id查询资源信息
        List<Permission> permissionByUid = userService.getPermissionByUid(userByUserName.getId());
        for (Permission one : permissionByUid) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(one.getKeyword());
            list.add(simpleGrantedAuthority);
        }

        return new org.springframework.security.core.userdetails.User(userByUserName.getUsername(),userByUserName.getPassword(),list);
    }
}
